package com.kfyty.loveqq.sa.token.sso.client;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.http.SaHttpTemplate;
import cn.dev33.satoken.sso.processor.SaSsoClientProcessor;
import cn.dev33.satoken.sso.template.SaSsoClientTemplate;
import cn.dev33.satoken.stp.StpUtil;
import com.kfyty.loveqq.framework.core.autoconfig.annotation.Autowired;
import com.kfyty.loveqq.framework.core.exception.ResolvableException;
import com.kfyty.loveqq.framework.web.core.annotation.RequestMapping;
import com.kfyty.loveqq.framework.web.core.annotation.RestController;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

/**
 * Sa-Token-SSO Client端 Controller
 */
@Slf4j
@RestController
public class SsoClientController {
    private static final HttpClient client = HttpClient.newHttpClient();

    /**
     * 首页
     */
    @RequestMapping(value = "/", produces = "text/html; charset=utf-8")
    public String index() {
        return "<h2>Sa-Token SSO-Client 应用端 (模式二)</h2>" +
                "<p>当前会话是否登录：" + StpUtil.isLogin() + " (" + StpUtil.getLoginId("") + ")</p>" +
                "<p> " +
                "<a href='/sso/login?back=/'>登录</a> - " +
                "<a href='/sso/logoutByAlone?back=/'>单应用注销</a> - " +
                "<a href='/sso/logout?back=self'>全端注销</a> - " +
                "<a href='/sso/myInfo' target='_blank'>账号资料</a>" +
                "</p>";
    }

    /**
     * SSO-Client端：处理所有SSO相关请求
     *         http://{host}:{port}/sso/login            -- Client 端登录地址
     *         http://{host}:{port}/sso/logout            -- Client 端注销地址（isSlo=true时打开）
     *         http://{host}:{port}/sso/pushC            -- Client 端接收消息推送地址
     */
    @RequestMapping(value = "/sso/*", produces = "text/html; charset=utf-8")
    public Object ssoRequest() {
        return SaSsoClientProcessor.instance.dister();
    }

    /**
     * 当前应用独自注销 (不退出其它应用)
     */
    @RequestMapping(value = "/sso/logoutByAlone", produces = "text/html; charset=utf-8")
    public Object logoutByAlone() {
        StpUtil.logout();
        return SaSsoClientProcessor.instance._ssoLogoutBack(SaHolder.getRequest(), SaHolder.getResponse());
    }

    /**
     * 配置SSO相关参数
     */
    @Autowired
    public void configSso(SaSsoClientTemplate ssoClientTemplate) {
        SaManager.setSaHttpTemplate(new SaHttpTemplate() {

            @Override
            public String get(String url) {
                try {
                    return client.send(HttpRequest.newBuilder(URI.create(url)).build(), HttpResponse.BodyHandlers.ofString()).body();
                } catch (Exception e) {
                    throw new ResolvableException(e);
                }
            }

            @Override
            public String postByFormData(String url, Map<String, Object> params) {
                throw new UnsupportedOperationException();
            }
        });

        log.info("config sso");
    }
}
